import React, { useState, useEffect } from 'react';
import { Button, Form, Popconfirm } from 'antd';
import { isEqual } from 'lodash';
import EditTable from './EditTable';
import { genID } from '../util';
import Successor from './Successor';

const WorkCountersign = ({ value, onChange, config }) => {
    const [dataSource, setDataSource] = useState(
        value || [
            {
                id: genID(10),
                projectName: '',
                workContent: '',
                workLink: '',
                successor: '',
                isValidatorPass: false
            }
        ]
    );
    const [columns, setColumns] = useState([]);
    const { disabled } = config?.options;

    // 添加
    const handleAdd = () => {
        const newData = {
            id: genID(10),
            projectName: '',
            workContent: '',
            workLink: '',
            successor: '',
            isValidatorPass: false
        };
        setDataSource([...dataSource, newData]);
    };

    // 编辑行变化保存
    const handleRowSave = row => {
        // console.log('== ==========>row', row);
        const newData = dataSource;
        const index = newData.findIndex(item => row.id === item.id);
        const item = newData[index];
        newData.splice(index, 1, {
            ...item,
            ...row
        });
        setDataSource([...newData]);
    };

    // 删除
    const handleDelete = record => {
        const arr = dataSource.filter(item => item.id !== record.id);
        setDataSource([...arr]);
    };

    useEffect(() => {
        console.log('sddddddd');
        const tempColumns = [
            {
                title: '交接事项',
                dataIndex: 'projectName',
                width: '20%',
                editable: true,
                rules: [
                    {
                        required: true,
                        message: '交接事项不能为空！'
                    }
                ]
            },
            {
                title: '工作描述',
                dataIndex: 'workContent',
                width: '20%',
                editable: true,
                rules: [
                    {
                        required: true,
                        message: '工作描述不能为空！'
                    }
                ]
            },
            {
                title: '相关链接',
                dataIndex: 'workLink',
                width: '20%',
                editable: true
            },
            {
                title: '交接人',
                dataIndex: 'successor',
                width: '20%',
                editable: true,
                editrender: ({ record, save, form, dataIndex, title }) => (
                    <>
                        <Form.Item style={{ margin: 0 }}>
                            {form.getFieldDecorator(dataIndex, {
                                rules: [
                                    {
                                        required: true,
                                        message: `${title}必选`
                                    }
                                ],
                                initialValue: record[dataIndex] || undefined
                            })(<Successor onPressEnter={save} onBlur={save} placeholder={`请选择${title}`} />)}
                        </Form.Item>
                    </>
                ),
                render: text => text?.label
            },
            {
                title: '操作',
                dataIndex: 'operation',
                width: '20%',
                render: (text, record) => (
                    <Popconfirm title="确认删除？" onConfirm={() => handleDelete(record)}>
                        <Button type="link">删除</Button>
                    </Popconfirm>
                )
            }
        ];
        setColumns([...tempColumns]);
    }, [dataSource, value]);

    useEffect(() => {
        if (value && onChange) {
            onChange(dataSource);
        }
    }, [dataSource]);

    // 权限控制列展示
    useEffect(() => {
        if (disabled && disabled === true && columns.length > 0) {
            const arr = columns
                .filter(item => item.dataIndex !== 'operation')
                .map(item => ({ ...item, editable: false }));
            if (!isEqual(arr, columns)) {
                setColumns([...arr]);
            }
        }
    }, [disabled, columns]);

    return (
        <div>
            <EditTable dataSource={dataSource} columns={columns} handleRowSave={handleRowSave} rowKey="id" />
            {disabled === false && (
                <Button type="dashed" onClick={handleAdd} block style={{ marginTop: 16 }}>
                    <span style={{ fontSize: 18, marginRight: 3 }}>+</span> 添加
                </Button>
            )}
        </div>
    );
};

export default React.forwardRef(WorkCountersign);
